<template>
  <view class="details-wrap u-skeleton" :data-theme="globPrimary">
    <view class="edu-navbar-fixed" :style="{ height: globStatusBarHeight + 'px' }"></view>
    <view :style="{ width: '100%', height: globStatusBarHeight + 'px' }"></view>
    <u-navbar
      class="navbar-wrapper"
      :class="{ active: opacity < 1 }"
      :is-back="false"
      :border-bottom="false"
      back-icon-color="#fff"
      :immersive="true"
      :background="backgroundColor"
    >
      <view class="round" @tap="onBack"
        ><u-icon name="nav-back" color="#fff" size="30"></u-icon
      ></view>
      <view v-show="opacity >= 1" class="navbar-title u-line-1" :style="[titleStyle]"
        >课程详情</view
      >
      <view slot="right" class="right">
        <view class="round" @click="onCollected">
          <u-icon :name="collected ? 'star-fill' : 'star'" color="#FF8A52" size="30"></u-icon>
        </view>
        <view class="round" @click="inviteBargain"
          ><u-icon name="zhuanfa" color="#fff" size="30"></u-icon
        ></view>
      </view>
    </u-navbar>
    <mescroll-body
      :sticky="true"
      :down="{ use: false }"
      :up="{ empty: { use: false } }"
      :height="mescrollHeight"
      ref="mescrollRef"
      @init="mescrollInit"
      @up="upCallback"
    >
      <view class="u-rela">
        <edu-image :height="415" :src="detailsInfo.cover_url"></edu-image>
        <!-- 活动板块 -->
        <promotion
          v-if="!$u.test.empty(detailsInfo.promotion) && detailsInfo.is_buy == 0"
          :data="detailsInfo.promotion"
        ></promotion>
      </view>
      <view class="details-header">
        <view class="header-title u-line-1 u-skeleton-rect">
          <u-tag
            text="连载"
            type="success"
            mode="plain"
            size="mini"
            v-if="detailsInfo.update_status == 1"
          />
          <view class="title u-line-1">{{ detailsInfo.title }}</view>
        </view>
        <view class="header-info u-flex u-row-between u-skeleton-rect">
          <view class="u-flex">
            <view class="score">
              {{ detailsInfo.score_star }}分
              <u-rate
                v-model="detailsInfo.score_star"
                :disabled="true"
                inactive-color="#DCDFE6"
                active-color="#FF8A52"
                inactive-icon="star-fill"
              ></u-rate>
            </view>
            <view class="count">{{ detailsInfo.sale_count }}人在学</view>
          </view>
          <view class="u-flex">
            <view class="free" v-if="detailsInfo.user_price == 0">免费</view>
            <view class="price" v-else-if="detailsInfo.user_price > 0">{{
              detailsInfo.user_price | formatCurrency
            }}</view>
            <view class="price-bing" v-if="detailsInfo.scribing_price > 0">{{
              detailsInfo.scribing_price | formatCurrency(null, 0)
            }}</view>
          </view>
        </view>
        <template v-if="!$u.test.empty(detailsInfo)">
          <template v-if="detailsInfo.is_buy == 0">
            <view class="time-yx u-skeleton-rect" v-if="detailsInfo.term_time == 0">永久有效</view>
            <view class="time-yx" v-else-if="detailsInfo.term_time < 10000"
              >购买之日起<text style="color: #f54030">{{ detailsInfo.term_time }}</text
              >天内有效</view
            >
            <view class="time-yx" v-else>{{ detailsInfo.term_time | handleTime }}前有效</view>
          </template>
          <template v-else>
            <view class="time-yx" v-if="detailsInfo.term_rest == -1">永久有效</view>
            <view class="time-yx" v-else
              >距离课程到期还有<text style="color: #f54030">{{
                formatTime(detailsInfo.term_rest)
              }}</text
              >天</view
            >
          </template>
        </template>
      </view>
      <view class="header-coupon" v-if="!loading && !$u.test.empty(detailsInfo.recommend_coupon)">
        <u-cell-group :border="false">
          <u-cell-item :border-bottom="false" hover-class="none" @click="openCoupon">
            <template slot="title">
              <view class="coupon-item u-flex u-flex-wrap">
                <view
                  class="coupon"
                  v-for="(item, index) in detailsInfo.recommend_coupon"
                  :key="index"
                >
                  <u-tag
                    :text="item"
                    mode="plain"
                    border-color="#FF8A52"
                    color="#FF8A52"
                    size="mini"
                    v-if="index < 3"
                  />
                </view>
              </view>
            </template>
            <u-image
              slot="icon"
              width="48"
              height="48"
              src="@/pageCourse/static/images/icon_quan.png"
            ></u-image>
          </u-cell-item>
        </u-cell-group>
      </view>
      <view class="header-teacher">
        <scroll-view scroll-x="true" class="scroll-view">
          <view class="u-flex">
            <view
              class="item u-flex"
              :class="{
                'item-1': teacherItemCol == 1,
                'item-2': teacherItemCol == 2,
                'item-3': teacherItemCol == 3,
              }"
              v-if="!$u.test.empty(detailsInfo.mhm_info)"
              @click="handleSchool()"
            >
              <u-avatar :src="detailsInfo.mhm_info.logo_url" size="100"></u-avatar>
              <view class="right">
                <view class="title u-line-1">
                  {{ detailsInfo.mhm_info.title }}
                </view>
                <view class="text">所属机构</view>
              </view>
            </view>
            <template v-if="!$u.test.empty(detailsInfo.teachers)">
              <view
                v-for="(item, index) in detailsInfo.teachers"
                :key="index"
                @click="toUser('/pageFound/user/index', item.user_id)"
                class="item u-flex"
                :class="{
                  'item-1': teacherItemCol == 1,
                  'item-2': teacherItemCol == 2,
                  'item-3': teacherItemCol == 3,
                }"
              >
                <view class="u-flex u-skeleton-circle">
                  <u-avatar :src="item.avatar_url" size="100"></u-avatar>
                </view>
                <view class="right" v-if="detailsInfo.teachers.length == 1">
                  <view class="u-flex u-skeleton-rect">
                    <view class="title u-line-1">
                      {{ item.title }}
                    </view>
                    <u-image
                      width="57"
                      height="32"
                      :src="item.icon_url"
                      v-if="item.icon_url"
                    ></u-image>
                  </view>
                  <view class="content u-skeleton-rect">
                    <view class="text u-line-1">{{ item.signature }}</view>
                  </view>
                </view>
                <view class="right" v-else>
                  <view class="u-flex u-skeleton-rect">
                    <view class="title u-line-1">{{ item.title }}</view>
                  </view>
                  <view class="content u-skeleton-rect">
                    <u-image
                      width="57"
                      height="32"
                      :src="item.icon_url"
                      v-if="item.icon_url"
                    ></u-image>
                  </view>
                </view>
              </view>
            </template>
          </view>
        </scroll-view>
      </view>
      <view class="tab-wrapper u-skeleton-rect">
        <u-sticky :enable="enable">
          <u-tabs-swiper
            ref="uTabs"
            :list="tabList"
            :current="tabCurrent"
            @change="tabsChange"
            :active-color="globPrimaryColor"
            :is-scroll="false"
            :bold="false"
            bar-height="4"
            :bar-style="{ bottom: 0 }"
            :offset="[10, -10]"
            class="tab-header"
          ></u-tabs-swiper>
          <u-line color="#F7F7F7" />
        </u-sticky>
        <view v-show="swiperCurrent == 'content'" class="u-rela content">
          <!-- #ifndef APP-PLUS -->
          <u-parse :html="detailsInfo.info"></u-parse>
          <!-- #endif -->
          <!-- #ifdef APP-PLUS -->
          <u-parse :html="detailsInfo.info_text"></u-parse>
          <!-- #endif -->
        </view>
        <!-- 目录 -->
        <view v-show="swiperCurrent == 'directory'">
          <classesDirectory
            v-if="detailsInfo.course_type == 4"
            :course-id="detailsInfo.id"
            :detailsInfo="detailsInfo"
          ></classesDirectory>
          <Section
            :course-id="detailsInfo.id"
            :detailsInfo="detailsInfo"
            v-if="detailsInfo.course_type == 1 || detailsInfo.course_type == 2"
          ></Section>
        </view>
        <!-- 评论 -->
        <Comment
          ref="courseComment"
          :detailsInfo="detailsInfo"
          v-show="swiperCurrent == 'comment'"
        ></Comment>
        <!-- 学员 -->
        <Student
          ref="courseStudent"
          v-show="swiperCurrent == 'student'"
          :detailsInfo="detailsInfo"
        ></Student>
        <!-- 考试 -->
        <Examation
          v-show="swiperCurrent == 'exam'"
          :can_exam="detailsInfo.can_exam"
          :exam="detailsInfo.exam"
          :is_buy="detailsInfo.is_buy"
          :course_id="detailsInfo.id"
        ></Examation>
        <course-file
          v-if="swiperCurrent == 'file'"
          :course_id="detailsInfo.id"
          :course_buy="detailsInfo.is_buy"
        ></course-file>
      </view>
    </mescroll-body>

    <SubmitBar
      :courseInfo="detailsInfo"
      @click="getDetailsInfo(courseId)"
      v-show="!loading"
    ></SubmitBar>
    <!-- 卡卷 -->
    <coupon-popup :visible.sync="showCoupon" :coureId="courseId"></coupon-popup>

    <u-skeleton :loading="loading" el-color="#F7F7F7" bg-color="transparent"></u-skeleton>

    <edu-user-coupon></edu-user-coupon>
  </view>
</template>

<script>
import classesDirectory from './components/classesDirectory.vue'
import Section from './components/section.vue'
import Student from './components/student.vue'
import SubmitBar from './components/submitBar.vue'
import CouponPopup from './components/coupon-popup.vue'
import Promotion from './components/promotion.vue'
import Comment from './comment/index.vue'
import Examation from './components/examination.vue'
import CourseFile from './components/courseFile.vue'
import { mapState, mapGetters } from 'vuex'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
export default {
  mixins: [MescrollMixin],
  components: {
    classesDirectory,
    Section,
    Student,
    SubmitBar,
    Comment,
    Promotion,
    Examation,
    CouponPopup,
    CourseFile,
  },
  data() {
    return {
      loading: true,
      backgroundColor: { backgroundColor: 'transparent' },
      opacity: 0,
      detailsInfo: {
        title: '默认课程标题',
        cover_url: '',
        score_star: 0,
        sale_count: 0,
        user_price: 1,
        scribing_price: 1,
        term_time: 0,
        is_buy: 0,
        info: '默认内容',
        info_text: '默认内容',
        teachers: [
          {
            title: '平台默认讲师',
            level_text: '平台默认等级',
            signature: '简介',
          },
        ],
      },
      // 因为内部的滑动机制限制，请将tabs组件和swiper组件的current用不同变量赋值
      tabCurrent: 0, // tabs组件的current值，表示当前活动的tab选项
      swiperCurrent: 'content', // swiper组件的current值，表示当前那个swiper-item是活动的
      enable: true,
      showCoupon: false,
      courceType: { 1: 'video', 2: 'live', 3: 'offline', 4: 'classes' },
      courseId: 0,
    }
  },
  computed: {
    ...mapState({
      getCurrentPlayItem: (state) => state.course.currentPlayItem,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globCommentSwitch: 'projectSetting/getGlobCourseCommentSwitch',
      globCoursewareSwitch: 'projectSetting/getGlobCoursewareSwitch',
      globCourseExamSwitch: 'projectSetting/getGlobCourseExamSwitch',
      globWindowHeight: 'projectSetting/globWindowHeight',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
    }),
    collected() {
      return this.detailsInfo.collected
    },
    tabList() {
      let arr = [
        { name: '简介', key: 'content' },
        { name: '目录', key: 'directory' },
      ]
      let audition = this.detailsInfo.audition_stat == 1 && this.detailsInfo.is_buy === 0
      if (this.globCommentSwitch) {
        arr.push({ name: '评论', key: 'comment' })
      }
      if (this.detailsInfo.course_type == 4) {
        arr.push({ name: '学员', key: 'student' })
      }
      if (this.globCourseExamSwitch == 1) {
        arr.push({ name: '考试', key: 'exam' })
      }
      if (this.globCoursewareSwitch == 1) {
        arr.push({ name: '课件', key: 'file' })
      }
      let directoryIndex = arr.findIndex((item) => item.key == 'directory')
      if (audition) {
        arr[directoryIndex].count = '试看'
      }
      return arr
    },
    mescrollHeight() {
      let height = this.globWindowHeight - this.globStatusBarHeight - 56
      return `${height}px`
    },
    // 导航中间的标题的样式
    titleStyle() {
      let titleWidth = 250
      let systemInfo = uni.getSystemInfoSync()
      let style = {}
      // #ifndef MP
      style.left = (systemInfo.windowWidth - uni.upx2px(titleWidth)) / 2 + 'px'
      style.right = (systemInfo.windowWidth - uni.upx2px(titleWidth)) / 2 + 'px'
      // #endif
      // #ifdef MP
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      let rightButtonWidth = systemInfo.windowWidth - menuButtonInfo.left
      style.left = (systemInfo.windowWidth - rightButtonWidth - uni.upx2px(titleWidth)) / 2 + 'px'
      style.right =
        (systemInfo.windowWidth - rightButtonWidth - uni.upx2px(titleWidth)) / 2 +
        rightButtonWidth +
        'px'
      // #endif
      style.width = uni.upx2px(titleWidth) + 'px'
      return style
    },
    teacherItemCol() {
      let num = 0
      if (!this.$u.test.empty(this.detailsInfo.mhm_info)) num = 1
      if (!this.$u.test.empty(this.detailsInfo.teachers)) num = 1
      if (
        !this.$u.test.empty(this.detailsInfo.mhm_info) &&
        !this.$u.test.empty(this.detailsInfo.teachers)
      ) {
        if (this.detailsInfo.teachers.length == 1) {
          num = 2
        } else {
          num = 3
        }
      }
      return num
    },
  },
  filters: {
    handleTime(timeStamp) {
      if (timeStamp > 0) {
        var date = new Date()
        date.setTime(timeStamp * 1000)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        var second = date.getSeconds()
        minute = minute < 10 ? '0' + minute : minute
        second = second < 10 ? '0' + second : second
        return y + '年' + m + '月' + d + '日'
      } else {
        return ''
      }
    },
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  onPageScroll(e) {
    this.pageScroll(e)
  },
  onShareAppMessage(res) {
    return {
      title: this.detailsInfo.title,
      path: '/pageCourse/course/details?id=' + this.courseId,
    }
  },
  onLoad(options) {
    if (options.share_code) {
      this.$store.commit('projectSetting/setShareCode', options.share_code)
    }
    this.courseId = options.id
  },
  onUnload() {
    // 移除监听事件
    uni.$off('sectionItemUpdate')
    uni.$off('courseTabUpdate')
  },
  onShow() {
    this.enable = true
    this.getDetailsInfo(this.courseId)
  },
  onHide() {
    this.enable = false
  },
  mounted() {
    uni.$on('courseTabUpdate', () => {
      this.mescroll.resetUpScroll()
    })
  },
  options: { styleIsolation: 'shared' },
  methods: {
    getDetailsInfo(id) {
      this.$edu.api.getCourseDetails(id).then((res) => {
        const { data } = res
        this.detailsInfo = data
        // 更新目录数据
        uni.$emit('sectionItemUpdate', {
          course_type: data.course_type,
        })
        setTimeout(() => {
          this.loading = false
        }, 50)
      })
    },
    // tabs通知swiper切换
    tabsChange(index) {
      this.tabCurrent = index
      this.swiperCurrent = this.tabList[index].key
      this.$nextTick(() => {
        this.mescroll.resetUpScroll()
        this.mescroll.scrollTo(0, 0)
      })
    },
    upCallback(page) {
      if (this.swiperCurrent == 'comment') {
        this.$refs.courseComment.getCommentList(page, this.mescroll)
      } else if (this.swiperCurrent == 'student')
        this.$refs.courseStudent.getStudentsList(page, this.mescroll)
      {
        this.mescroll.endSuccess(0)
      }
    },
    // 导航栏渐变
    pageScroll(e) {
      let color = this.globPrimaryColor
      let tmpY = 320
      if (e.scrollTop > tmpY) {
        this.opacity = 1
      } else {
        this.opacity = (e.scrollTop - 260) / 60
      }
      let rgba = this.$u.colorToRgba(color, this.opacity)
      this.backgroundColor = { backgroundColor: rgba }
    },
    // 打开卡卷弹窗
    openCoupon() {
      this.$edu.judgeLogin(() => {
        this.showCoupon = true
      })
    },
    // 分享
    inviteBargain() {
      this.$edu.judgeLogin(() => {
        this.$u.route('/pageCourse/course/share', {
          type: 1,
          id: this.courseId,
        })
      })
    },
    // 收藏
    onCollected() {
      this.$edu.judgeLogin(() => {
        if (this.detailsInfo.collected) {
          this.$edu.api
            .deleteCollection({
              source_type: this.courceType[this.detailsInfo.course_type],
              source_id: this.detailsInfo.id,
            })
            .then((res) => {
              this.$u.toast(res.msg)
              this.detailsInfo.collected = 0
            })
        } else {
          this.$edu.api
            .createCollection({
              source_type: this.courceType[this.detailsInfo.course_type],
              source_id: this.detailsInfo.id,
            })
            .then((res) => {
              this.$u.toast(res.msg)
              this.detailsInfo.collected = 1
            })
        }
      })
    },
    // 机构
    handleSchool() {
      // #ifdef H5
      window.location.href = `${this.detailsInfo.mhm_sdn}`
      // #endif
      // #ifndef H5
      this.$u.route('pageFound/school/home', {
        id: this.detailsInfo.mhm_info.id,
      })
      // #endif
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      var cuccpage = pages[pages.length - 1]
      if (this.$u.test.empty(page)) {
        this.$u.route({ type: 'switchTab', url: 'pages/course/index' })
      } else {
        if (page.route == cuccpage.route) {
          this.$u.route({ type: 'switchTab', url: 'pages/course/index' })
        } else {
          this.$u.route({ type: 'back' })
        }
      }
    },
    toUser(url, id) {
      this.$edu.route(url, {
        id: id,
      })
    },
    // 天
    formatTime(seconds) {
      let day = Math.ceil(seconds / (24 * 3600))
      return day
    },
  },
}
</script>

<style lang="scss" scoped>
.edu-navbar-fixed {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 100;
  background: #ffffff;
}
.navbar-title {
  position: absolute;
  left: 0;
  right: 0;
  font-size: 16px;
  text-align: center;
  font-weight: 500;
  color: #ffffff;
}
.navbar-wrapper {
  /deep/.u-navbar-inner {
    padding: 0 30rpx;
  }
  .right {
    display: flex;
  }
  &.active {
    .round {
      background: rgba(0, 0, 0, 0.4);
    }
  }
  .round {
    width: 58rpx;
    height: 58rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }
  .round + .round {
    margin-left: 32rpx;
  }
}

.details-wrap {
  .details-header {
    padding: 30rpx 30rpx;
    background-color: #ffffff;
    .header-title {
      display: flex;
      align-items: center;

      ::v-deep.u-tag {
        display: block;
      }
      .title {
        margin-left: 10rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: $edu-main-color;
      }
    }
    .header-info {
      margin-top: 20rpx;
      .score {
        font-size: 26rpx;
        color: #ff8a52;
      }
      .count {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: $edu-tips-color;
      }
      .price-bing {
        font-size: 26rpx;
        font-weight: 400;
        color: $edu-tips-color;
        text-decoration: line-through;
        margin-right: 8rpx;
      }
      .free {
        font-size: 34rpx;
        font-weight: 500;
        color: $edu-free-color;
      }
      .price {
        font-size: 36rpx;
        font-weight: 600;
        color: $edu-price-color;
      }
    }
    .time-yx {
      height: 37rpx;
      line-height: 37rpx;
      font-size: 26rpx;
      color: #909399;
      margin-top: 29rpx;
    }
  }
  .header-coupon {
    background-color: #ffffff;
    margin-top: 8rpx;
    .coupon-item {
      padding: 0 22rpx;
      /* #ifdef MP-WEIXIN */
      .coupon {
        margin-left: 10rpx;
      }
      /* #endif */
      .u-tag {
        margin: 4rpx 10rpx;
      }
    }
  }
  .header-teacher {
    padding-left: 30rpx;
    background-color: #ffffff;
    margin-top: 8rpx;
    .scroll-view {
      white-space: nowrap !important;
    }
    uni-swiper {
      width: 100%;
      height: 160rpx;
    }
    .item {
      padding: 30rpx 30rpx 30rpx 0;
      white-space: nowrap;
    }
    .title {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-main-color;
    }
    .right {
      margin-left: 10rpx;
      flex: 1;
      min-width: 0;
      .u-image {
        margin-left: 8rpx;
      }
    }
    .content {
      margin-top: 10rpx;
    }
    .text {
      font-size: 26rpx;
      font-weight: 400;
      color: $edu-tips-color;
    }
    .item-1 {
      width: calc(100vw - 30rpx);
    }
    .item-2 {
      width: calc(calc(100vw - 30rpx) / 2);
    }
    .item-3 {
      width: 276rpx;
      .title {
        width: 100%;
        margin-right: 0;
      }
    }
  }

  .tab-wrapper {
    margin-top: 8rpx;
    min-height: 100px;
    background-color: #ffffff;
    .content {
      padding: 30rpx;
      text-align: justify;
    }
  }

  .tab-header {
    /deep/.u-badge {
      background-color: $edu-type-success;
      padding: 6rpx 13rpx;
      border-radius: 9rpx 9rpx 9rpx 0;
    }
  }
}
</style>
